<script setup>
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import dataTxt from '@/data.txt?raw'
import dataVideoTxt from '@/data_video.txt?raw'
import ws from '@/services/websocket'
import audio from '@/services/audio'
import click from '@/services/clickSound'


//分离图片的url
const urls = dataTxt
  .split(/\r?\n/)
  .map(s => s.trim())
  .filter(Boolean)

//分离视频的url
const videoUrls = dataVideoTxt
  .split(/\r?\n/)
  .map(s => s.trim())
  .filter(Boolean)

//计算图片的数量
const totalFiles = urls.length
const completedFiles = ref(0)

//计算视频的数量
const totalVideoFiles = videoUrls.length
const completedVideoFiles = ref(0)

const started = ref(false)
const totalBytesKnown = ref(0)
const totalBytesDownloaded = ref(0)

// 阶段：preloading -> loading-videos -> connecting -> connected / error
const phase = ref('preloading')
const titleText = computed(() => {
  if (phase.value === 'preloading') return '正在加载资源文件'
  if (phase.value === 'loading-videos') return '正在加载视频文件'
  if (phase.value === 'connecting') return '正在尝试连接服务器'
  if (phase.value === 'connected') return '连接成功！请允许进入全屏以继续'
  return '连接失败，请稍后重试'
})

const router = useRouter()
//计算进度
const progressPercent = computed(() => {
  if (totalBytesKnown.value > 0) {
    return Math.floor((totalBytesDownloaded.value / totalBytesKnown.value) * 100)
  }
  if (phase.value === 'preloading') {
    if (totalFiles === 0) return 100
    return Math.floor((completedFiles.value / totalFiles) * 100)
  }
  if (phase.value === 'loading-videos') {
    if (totalVideoFiles === 0) return 100
    return Math.floor((completedVideoFiles.value / totalVideoFiles) * 100)
  }
  return 100
})

async function fetchWithProgress(url, isVideo = false) {
  try {
    const res = await fetch(url, { mode: 'cors' })
    const lengthHeader = res.headers.get('content-length')
    const expected = lengthHeader ? Number(lengthHeader) : 0
    if (expected > 0) totalBytesKnown.value += expected

    if (!res.body) {
      await res.blob()
      if (isVideo) {
        completedVideoFiles.value++
      } else {
        completedFiles.value++
      }
      return
    }

    const reader = res.body.getReader()
    for (;;) {
      const { done, value } = await reader.read()
      if (done) break
      const chunkSize = value ? value.length : 0
      totalBytesDownloaded.value += chunkSize
    }
    if (isVideo) {
      completedVideoFiles.value++
    } else {
      completedFiles.value++
    }
  } catch (_) {
    if (isVideo) {
      completedVideoFiles.value++
    } else {
      completedFiles.value++
    }
  }
}

async function startPreload() {
  if (started.value) return
  started.value = true

  // 第一阶段：加载图片资源
  // Limit concurrency to avoid overwhelming network
  const CONCURRENCY = 6
  let index = 0

  async function worker() {
    while (index < urls.length) {
      const myIndex = index++
      const url = urls[myIndex]
      await fetchWithProgress(url, false)
    }
  }

  const workers = Array.from({ length: Math.min(CONCURRENCY, urls.length) }, worker)
  await Promise.all(workers)

  // 图片加载完成，开始加载视频
  phase.value = 'loading-videos'
  
  // 重置进度计数器用于视频加载
  totalBytesKnown.value = 0
  totalBytesDownloaded.value = 0
  
  // 第二阶段：加载视频资源
  if (videoUrls.length > 0) {
    let videoIndex = 0
    
    async function videoWorker() {
      while (videoIndex < videoUrls.length) {
        const myIndex = videoIndex++
        const url = videoUrls[myIndex]
        await fetchWithProgress(url, true)
      }
    }
    
    const videoWorkers = Array.from({ length: Math.min(2, videoUrls.length) }, videoWorker)
    await Promise.all(videoWorkers)
  }

  // 视频加载完成，开始连接服务器
  phase.value = 'connecting'
  // 初始化背景音乐（不自动播放，等待用户手势）
  try {
    audio.init('http://117.72.17.45:5500/data/bks/bkmusic.mp3', { loop: true, volume: 0.3 })
    click.init('http://117.72.17.45:5500/data/bks/click.mp3', { size: 6, volume: 0.8 })

  } catch (_) {}
  try {
    await ws.init()
    phase.value = 'connected'
    // 等待用户授予全屏权限后再进入主页面
  } catch (e) {
    phase.value = 'error'
  }
}

async function enterFullscreenAndContinue() {
  const el = document.documentElement
  try {
    if (el.requestFullscreen) await el.requestFullscreen()
    else if (el.webkitRequestFullscreen) await el.webkitRequestFullscreen()
    else if (el.msRequestFullscreen) await el.msRequestFullscreen()
    
  } catch (_) {
    return
  }
  //try { await audio.play() } catch (_) {}
  router.replace('/login')
}

onMounted(() => {
  //开始加载图片资源
  startPreload()
})

</script>

<template>
  <div class="loading">
    <div class="title">{{ titleText }}</div>
    <div class="progress">
      <span v-if="phase === 'preloading'">图片加载进度：{{ progressPercent }}%（{{ completedFiles }} / {{ totalFiles }}）</span>
      <span v-else-if="phase === 'loading-videos'">视频加载进度：{{ progressPercent }}%（{{ completedVideoFiles }} / {{ totalVideoFiles }}）</span>
      <span v-else>加载进度：{{ progressPercent }}%</span>
    </div>
    <button v-if="phase === 'connected'" class="fullscreen-btn" @click="enterFullscreenAndContinue">进入全屏并进入游戏</button>
  </div>
  
</template>

<style scoped>
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  width: 100%;
  gap: 8px;
  background: #e6f4ff;
}
.title {
  font-size: 20px;
}
.progress, .speed {
  color: #666;
}
.fullscreen-btn {
  margin-top: 12px;
  padding: 10px 16px;
  background: #1677ff;
  color: #fff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}
</style>


